package com.example.study.common.dataSourceConfig;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @description：多数据源上下文
 * @author: liqiancheng
 * @createTime: 2021/7/26 11:09
 **/
public class DynamicContextHolder {

    private static final ThreadLocal<Deque<String>> CONTEXT_HOLDER = new ThreadLocal() {
        @Override
        protected Object initialValue() {
            return new ArrayDeque();
        }
    };


    /**
     * @author:
     * @createTime: 2020/6/29 15:23
     * @description: 获得当前线程数据源
     * @param
     * @return 数据源名称
     */
    public static String peek() {
        return CONTEXT_HOLDER.get().peek();
    }

    /**
     * @author:
     * @createTime: 2020/6/29 15:23
     * @description: 设置当前线程数据源
     * @param dataSource 数据源名称
     */
    public static void push(String dataSource) {
        CONTEXT_HOLDER.get().push(dataSource);
    }

    /**
     * @author:
     * @createTime: 2020/6/29 15:23
     * @description: 清空当前线程数据源
     */
    public static void poll() {
        Deque<String> deque = CONTEXT_HOLDER.get();
        deque.poll();
        if (deque.isEmpty()) {
            CONTEXT_HOLDER.remove();
        }
    }
}
